from ..database import connect_to_database, close_database_connection
from datetime import date

def calculate_body_fat_percentage(height: float, weight: float, age: int, gender: int) -> float:
    """
    计算体脂率
    :param height: 身高 (米)
    :param weight: 体重 (公斤)
    :param age: 年龄
    :param gender: 性别 (男性为1，女性为0)
    :return: 体脂率
    """
    bmi = weight / (height ** 2)
    body_fat_percentage = (1.20 * bmi) + (0.23 * age) - (10.8 * gender) - 5.4
    return body_fat_percentage

def record_user_health_data(user_id: str, height: float, weight: float, age: int, gender: int):
    """
    记录用户的健康数据
    :param user_id: 用户ID
    :param height: 身高 (米)
    :param weight: 体重 (公斤)
    :param age: 年龄
    :param gender: 性别 (男性为1，女性为0)
    :return: 记录结果
    """
    body_fat_percentage = calculate_body_fat_percentage(height, weight, age, gender)
    db, ssh_tunnel = connect_to_database()
    query = """
    INSERT INTO user_health_data (user_id, date, height, weight, body_fat_percentage)
    VALUES (%s, %s, %s, %s, %s)
    """
    try:
        with db.cursor() as cursor:
            cursor.execute(query, (user_id, date.today(), height, weight, body_fat_percentage))
            db.commit()
            return {"message": "健康数据已成功记录。"}
    except Exception as e:
        db.rollback()
        raise Exception(f"Failed to record health data: {e}")
    finally:
        close_database_connection(db, ssh_tunnel)

def get_user_health_data(user_id: str, target_date: date):
    """
    获取用户的健康数据
    :param user_id: 用户ID
    :param target_date: 目标日期
    :return: 健康数据
    """
    db, ssh_tunnel = connect_to_database()
    query = """
    SELECT height, weight, body_fat_percentage
    FROM user_health_data
    WHERE user_id = %s AND date = %s
    """
    try:
        with db.cursor() as cursor:
            cursor.execute(query, (user_id, target_date))
            result = cursor.fetchone()

            if result:
                return {
                    "height": result[0],
                    "weight": result[1],
                    "body_fat_percentage": result[2]
                }
            else:
                return None
    except Exception as e:
        raise Exception(f"Database query error: {e}")
    finally:
        close_database_connection(db, ssh_tunnel)